package org.halo.trade.data.http;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

public class ResultResponseHandler implements ResponseHandler<HttpResult>
{
	@Override
	public HttpResult handleResponse(final HttpResponse response) throws ClientProtocolException, IOException
	{
		int status = response.getStatusLine().getStatusCode();
		HttpEntity entity = response.getEntity();
		// String ret= entity != null ? EntityUtils.toString(entity, "utf-8") :
		// null;
		// System.out.println(status+":"+ret);	
		// Header etag=response.getFirstHeader("Etag");
		// System.out.println(etag);
		
		HttpResult ret = new HttpResult();
		ret.status = status;
		ret.headers = response.getAllHeaders();
		ret.retstring = (entity != null) ? EntityUtils.toString(entity, "utf-8") : null;
		EntityUtils.consume(entity);

		if (status >= 200 && status < 300)
		{
			return ret;
		} else
		{
			throw new ClientProtocolException("Unexpected response status: " + status);
		}
	}
}
